﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Linq;

using ECCIT;
using ECCIT.Data;
using ECCIT.Business.DAL;

using OgilvyOne.UKNow.Common;
using OgilvyOne.UKNow.Globalization;
using OgilvyOne.UKNow.Utility;
using OgilvyOne.UKNow.Model;
using OgilvyOne.UKNow.IDAL;

namespace OgilvyOne.UKNow.DAL
{
    public class WarmupCommentDAL : UKNowBaseDAL, IDALWarmupComment
    {
        private const string TBL_NAME = "UKNOW_WARMUP_COMMENT";

        private const string COL_LANG_ID = "COL_LANG_ID";
        private const string COL_WARMUP_ID = "COL_WARMUP_ID";
        private const string COL_WARMUP_CMT_ID = "COL_WARMUP_CMT_ID";
        private const string COL_WARMUP_CMT_TEXT = "COL_WARMUP_CMT_TEXT";
        private const string COL_MEMBER_ID         = "COL_MEMBER_ID";
        private const string COL_WARMUP_CMT_TIME = "COL_WARMUP_CMT_TIME";
        private const string COL_WARMUP_CMT_STATE = "COL_WARMUP_CMT_STATE";
        private const string COL_WARMUP_SRC_CMT_ID = "COL_WARMUP_SRC_CMT_ID";
        private const string COL_WARMUP_SRC_MEMBER_ID = "COL_WARMUP_SRC_MEMBER_ID";

        public override string TableName { get { return TBL_NAME; } }

        public override Type ModelType { get { return typeof(WarmupCommentModel); } }

        [PrimaryKey]
        public IField LanguageID { get { return FieldFactory.Create(ModelType, "LanguageID", ColumnFactory.CreateColumn(COL_LANG_ID, DataType.Int)); } }
        [PrimaryKey]
        public IField ID { get { return FieldFactory.Create(ModelType, "ID", ColumnFactory.CreateColumn(COL_WARMUP_CMT_ID, DataType.Int)); } }
        
        public IField WarmupID { get { return FieldFactory.Create(ModelType, "WarmupID", ColumnFactory.CreateColumn(COL_WARMUP_ID, DataType.Int)); } }
        public IField Text { get { return FieldFactory.Create(ModelType, "Text", ColumnFactory.CreateColumn(COL_WARMUP_CMT_TEXT, DataType.String, 200)); } }
        public IField CommenterID { get { return FieldFactory.Create(ModelType, "CommenterID", ColumnFactory.CreateColumn(COL_MEMBER_ID, DataType.Int)); } }
        public IField Time { get { return FieldFactory.Create(ModelType, "Time", ColumnFactory.CreateColumn(COL_WARMUP_CMT_TIME, DataType.DateTime)); } }
        public IField State { get { return FieldFactory.Create(ModelType, "State", ColumnFactory.CreateColumn(COL_WARMUP_CMT_STATE, DataType.Int)); } }
        public IField SourceCommentID { get { return FieldFactory.Create(ModelType, "SourceCommentID", ColumnFactory.CreateColumn(COL_WARMUP_SRC_CMT_ID, DataType.Int)); } }
        public IField SourceCommenterID { get { return FieldFactory.Create(ModelType, "SourceCommenterID", ColumnFactory.CreateColumn(COL_WARMUP_SRC_MEMBER_ID, DataType.Int)); } }

        public override IField[] InsertFields { get { return new IField[] { LanguageID, ID, WarmupID, Text, CommenterID, Time, State, SourceCommentID, SourceCommenterID }; } }
        public override IField[] SelectFields { get { return InsertFields; } }
        public override IField[] UpdateFields { get { return InsertFields; } }

        public WarmupCommentDAL() { }

        public WarmupCommentDAL(LanguageType languageType) { this.Language = LanguageFactory.Create(languageType); }

        private void SetForeignKeyModel(WarmupCommentModel model)
        {
            if (model == null) return;
            if (model.CommenterID!=null)
            {
                model.Commenter = new MemberDAL().GetMemberModelByID(model.CommenterID);
            }
            
            model.Warmup = new WarmupDAL(this.Language.LanguageType).GetWarmupModelByID(model.WarmupID);

            if (model.SourceCommentID != null)
                model.SourceComment = GetWarmupCommentModelByID(model.SourceCommentID);

            if (model.SourceCommenterID != null)
                model.SourceCommenter = new MemberDAL().GetMemberModelByID(model.SourceCommenterID);
        }

        #region IDALWarmup Members

        public WarmupCommentModel GetWarmupCommentModelByID(int? id)
        {
            WarmupCommentModel model = (WarmupCommentModel)GetModelByPrimaryKey(this.GetType(), new KeyValuePair<IField, object>[] { new KeyValuePair<IField, object>(LanguageID, (int)this.Language.LanguageType), new KeyValuePair<IField, object>(this.ID, id) });
            SetForeignKeyModel(model);
            return model;
        }

        public IList<WarmupCommentModel> GetAllCommentsByWarmupID(int? warmupID)
        {
            string whereClause = string.Format(" WHERE {0}={1} AND {2}={3}", COL_WARMUP_ID, warmupID, COL_LANG_ID, (int)this.Language.LanguageType);
            IList<WarmupCommentModel> models = GetModels(whereClause, PagingParameterFactory.CreateNonPagingParameter(SortingParameterFactory.CreateInstance(Time.PropertyName, SortOrder.Desc))).List.Cast<WarmupCommentModel>().ToList();
            foreach (WarmupCommentModel model in models)
                SetForeignKeyModel(model);

            return models;
        }

        public PagingList GetPublishedCommentsByWarmupID(int? warmupID, PagingParameter pagingParams)
        {
            WhereClauseBuilder builder = WhereClauseBuilder.CreateInstance(SearchConditionJoinOperator.AND);
            builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_WARMUP_CMT_STATE, 1, SearchConditionOperator.Equals));
            builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_WARMUP_ID, warmupID, SearchConditionOperator.Equals));
            builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_LANG_ID, (int)this.Language.LanguageType, SearchConditionOperator.Equals));

            string whereClause = builder.ToSqlCommand();
            if (pagingParams == null)
                pagingParams = PagingParameterFactory.CreateNonPagingParameter(null);

            if (pagingParams.SortingParameter == null)  //如果没有排序参数，默认按照最后更新时间倒排序
                pagingParams.SortingParameter = SortingParameterFactory.CreateInstance(Time.PropertyName, SortOrder.Desc);

            PagingList list = GetModels(whereClause, pagingParams);
            foreach(WarmupCommentModel model in list.List)
                SetForeignKeyModel(model);

            return list;
        }

        public ResultInfo Save(WarmupCommentModel modelInfo)
        {
            if (modelInfo == null) throw new ArgumentNullException("modelInfo");

            ResultInfo result = new ResultInfo(false);

            try
            {
                int rowsAffected = 0;
                if (modelInfo.ID == null)   // insert
                {
                    modelInfo.ID = SqlUtil.GetMaxRecordID(TableName, COL_WARMUP_CMT_ID, COL_LANG_ID, (int)this.Language.LanguageType);
                    modelInfo.State = 1;    // 强制将状态置为已发布
                    rowsAffected = Insert(modelInfo, null);
                }
                else // update
                {
                    rowsAffected = UpdateByPrimaryKey(modelInfo, null);
                }

                if (rowsAffected > 0)
                {
                    result.Message = Language.GetAlertMessage(ModelType, Enums.Action.Save, Enums.ActionResult.Success);
                    result.Result = true;
                    result.ReturnObject = modelInfo;
                }
            }
            catch (Exception ex)
            {
                result.Exception = ex;
                result.Message = Language.GetAlertMessage(ModelType, Enums.Action.Save, Enums.ActionResult.Exception, ex);
            }

            return result;
        }

        public ResultInfo Delete(IList<int?> idList)
        {
            ResultInfo result = new ResultInfo(false);
            using (IDbConnection conn = DBHelper.GetDbConnection())
            {
                conn.Open();
                IDbTransaction trans = conn.BeginTransaction();
                try
                {
                    foreach (int? id in idList)
                        DeleteModelByPrimaryKey(trans, this.GetType(), new KeyValuePair<IField, object>[] { new KeyValuePair<IField, object>(LanguageID, (int)this.Language.LanguageType), new KeyValuePair<IField, object>(this.ID, id) });

                    trans.Commit();
                    result.Result = true;
                    result.Message = Language.GetAlertMessage(ModelType, Enums.Action.Delete, Enums.ActionResult.Success);
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    result.Message = Language.GetAlertMessage(ModelType, Enums.Action.Delete, Enums.ActionResult.Exception, ex);
                }
                finally
                {
                    trans.Dispose();
                }
            }

            return result;
        }

        public ResultInfo Publish(IList<int?> idList)
        {
            ResultInfo result = new ResultInfo(false);

            IField[] updatedFields = new IField[] { this.State };
            IDataParameter[] parms = DBHelper.GetDataParameters(updatedFields);
            parms[0].Value = 1;

            string ids = "";
            foreach (int? id in idList)
                ids += (ids == string.Empty) ? id.ToString() : "," + id.ToString();

            WhereClauseBuilder builder = WhereClauseBuilder.CreateInstance(SearchConditionJoinOperator.AND);
            builder.Conditions.Add(InSearchCondition.CreateInstance(COL_WARMUP_CMT_ID, DataType.Int, ids));
            builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_LANG_ID, (int)this.Language.LanguageType, SearchConditionOperator.Equals));

            string whereClause = builder.ToSqlCommand();
            string cmdText = DBHelper.GetUpdateCommandText(this.TableName, updatedFields, whereClause);

            try
            {
                DBHelper.ExecuteNonQuery(cmdText, parms);
                result.Result = true;
                result.Message = Language.GetAlertMessage(ModelType, Enums.Action.Publish, Enums.ActionResult.Success);
            }
            catch (Exception ex)
            {
                result.Message = Language.GetAlertMessage(ModelType, Enums.Action.Publish, Enums.ActionResult.Exception, ex);
            }

            return result;
        }

        public ResultInfo UnPublish(IList<int?> idList)
        {
            ResultInfo result = new ResultInfo(false);

            IField[] updatedFields = new IField[] { this.State };
            IDataParameter[] parms = DBHelper.GetDataParameters(updatedFields);
            parms[0].Value = 0;

            string ids = "";
            foreach (int? id in idList)
                ids += (ids == string.Empty) ? id.ToString() : "," + id.ToString();

            WhereClauseBuilder builder = WhereClauseBuilder.CreateInstance(SearchConditionJoinOperator.AND);
            builder.Conditions.Add(InSearchCondition.CreateInstance(COL_WARMUP_CMT_ID, DataType.Int, ids));
            builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_LANG_ID, (int)this.Language.LanguageType, SearchConditionOperator.Equals));

            string whereClause = builder.ToSqlCommand();
            string cmdText = DBHelper.GetUpdateCommandText(this.TableName, updatedFields, whereClause);

            try
            {
                DBHelper.ExecuteNonQuery(cmdText, parms);
                result.Result = true;
                result.Message = Language.GetAlertMessage(ModelType, Enums.Action.UnPublish, Enums.ActionResult.Success);
            }
            catch (Exception ex)
            {
                result.Message = Language.GetAlertMessage(ModelType, Enums.Action.UnPublish, Enums.ActionResult.Exception, ex);
            }

            return result;
        }

        #endregion
    }
}
